from PyQt6.QtWidgets import QApplication, QMainWindow,QMenu,QTableWidgetItem,QMessageBox
from PyQt6.QtGui import QAction
from ui.MainWindow_ui import Ui_MainWindow
from views.Dialog import MyDialog
from PyQt6.QtCore import pyqtSlot, Qt
from controller.MainController import MainController
import sys
from utils.OSUtils import clear_directory, init_directory
from utils.GlobalKeyListener import GlobalKeyListener

class MainWindow(Ui_MainWindow, QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        self.setupUi(self)
        init_directory()
        self.playing_index = 1

        # 控制器
        self.main_controller = MainController()
        self.main_controller.spider_thread.download_update_signal.connect(self.update_table_state)
        self.main_controller.spider_thread.download_finished_signal.connect(self.show_message)
        # 表格右键菜单
        self.main_tableWidget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.main_tableWidget.customContextMenuRequested.connect(self.showContextMenu_edit)
        # 表格左键点击事件
        self.main_tableWidget.clicked.connect(self.on_main_tableWidget_Clicked)

        # 输入文本的对话框
        self.dialog_window = MyDialog()
        self.dialog_window.update_btn_signal.connect(self.update_table)

        # 创建并启动全局按键监听线程
        self.global_key_listener = GlobalKeyListener()
        self.global_key_listener.key_released.connect(self.on_key_pressed)
        self.global_key_listener.start()

    # #--------------------------------------全局按键监听-----------------------------------------------------
    def on_key_pressed(self, key):
 
        table_count = self.main_tableWidget.rowCount()
        if table_count == 0:
            return
        
        if self.playing_index > table_count:
            self.playing_index = 1

        self.main_controller.play_music(self.playing_index)
        self.playing_index += 1


    # #-----------------------------------右键菜单的槽函数----------------------------------------------
    def insertRow(self):
        """ 表格插入下一行，在当前行的下一行
        """
        rowPosition = self.main_tableWidget.currentRow()
        # 当前位置插入
        self.dialog_window.setIndex(rowPosition)

        self.dialog_window.show()

    def deleteRow(self):
        """ 表格删除当前行
        """
        currentRow = self.main_tableWidget.currentRow()
        if currentRow >= 0:  # 检查是否有选中的行
            self.main_tableWidget.removeRow(currentRow)
            self.main_controller.remove_music(currentRow + 1)

    def downloadRow(self):
        """ 表格下载当前行
        """
        self.disable_state() # 禁用状态
        people_list = ["Yunyang", "Yunxi", "Yunjian", "Xiaoxiao"]
        people_index = self.people_comboBox.currentIndex()
        people_name = people_list[people_index]

        text_idx = self.main_tableWidget.currentRow()
        text = self.main_tableWidget.item(text_idx, 1).text()
        self.main_controller.download_one_mp3(text_idx, text, people_name)

    # #-----------------------------------按钮槽函数----------------------------------------------
    @pyqtSlot()
    def on_main_tableWidget_Clicked(self):
        """表格 点击事件
        """
        currentRow = self.main_tableWidget.currentRow()
        mp3_idx = currentRow + 1
        self.main_controller.play_music(mp3_idx)
        self.playing_index = mp3_idx + 1

    @pyqtSlot()
    def on_mainAddBtn_clicked(self):
        """ 添加文本按钮 点击事件
        """
        self.dialog_window.setIndex(-1)
        self.dialog_window.show()

    @pyqtSlot()
    def on_mainDownloadBtn_clicked(self):
        """下载按钮 点击事件
        """
        self.playing_index = 1
        all_rows = self.main_tableWidget.rowCount()
        if all_rows == 0:
            return

        self.disable_state() # 先禁用状态
        clear_directory("./audios")  # 删除目录


        # 清空下载状态
        for row_count in range(all_rows):
            self.main_tableWidget.setItem(row_count, 0, QTableWidgetItem(""))

        people_list = ["Yunyang", "Yunxi", "Yunjian", "Xiaoxiao"]
        people_index = self.people_comboBox.currentIndex()
        people_name = people_list[people_index]

        self.main_controller.download_all_mp3(self.main_tableWidget, all_rows, people_name)

    @pyqtSlot()
    def on_newTableBtn_clicked(self):
        """重新录入 点击事件
        """
        self.playing_index = 1
        self.main_tableWidget.clearContents()
        self.main_tableWidget.setRowCount(0)
        self.disable_state()
        clear_directory("./audios")  # 清除目录
        self.enable_state()  # 启用状态

    def showContextMenu_edit(self, pos):
        """展示右键菜单
        """
        item = self.main_tableWidget.itemAt(pos)
        if item is None:
            return

        menu = QMenu()
        insertAction = QAction("上方插入一行", self)
        insertAction.triggered.connect(self.insertRow)
        menu.addAction(insertAction)

        deleteAction = QAction("删除当前行", self)
        deleteAction.triggered.connect(self.deleteRow)
        menu.addAction(deleteAction)

        deleteAction = QAction("下载当前行", self)
        deleteAction.triggered.connect(self.downloadRow)
        menu.addAction(deleteAction)

        menu.exec(self.main_tableWidget.mapToGlobal(pos))
        

    # #--------------------------------signal槽函数----------------------------------------------
    def update_table(self, text, index=None):
        """ 更新表格， 输入dialog的signal回调
        """
        text = text.strip()
        if text == "":
            return
        if index < 0:
            row_count = self.main_tableWidget.rowCount()
        else:
            row_count = index

            self.main_controller.insert_music(row_count+1)  # 当右键新增时，负责重命名mp3文件, 传递music_id

        self.main_tableWidget.insertRow(row_count) # 负责前端显示

        text_item = QTableWidgetItem(text)
        self.main_tableWidget.setItem(row_count, 0, QTableWidgetItem(""))
        self.main_tableWidget.setItem(row_count, 1, text_item)

    
    def update_table_state(self, idx):
        """下载item 的 signal信号回调
        """
        self.main_tableWidget.item(idx, 0).setText("下载完成")

    def show_message(self, msg):
        """下载完成signal信号回调
        """
        self.enable_state()
        QMessageBox.information(self, "提示", msg)


    # #--------------------------------------禁用状态-----------------------------------------------------
    def disable_state(self):
        """ 禁用状态
        """
        self.main_controller.release_pygame_player() # 摧毁播放器
        self.main_tableWidget.setEnabled(False)  # 禁用表格
        self.newTableBtn.setEnabled(False)  # 不允许新建表格
        self.mainDownloadBtn.setEnabled(False)  # 不允许下载
        self.mainAddBtn.setEnabled(False)  # 不允许新增条目
        self.people_comboBox.setEnabled(False)  # 不允许选择人物

    def enable_state(self):
        """ 启用状态
        """
        self.main_controller.init_pygame_player() # 启用音乐
        self.main_tableWidget.setEnabled(True) # 启用表格
        self.newTableBtn.setEnabled(True)  # 不允许新建表格
        self.mainDownloadBtn.setEnabled(True)  # 不允许下载
        self.mainAddBtn.setEnabled(True)  # 允许新增条目
        self.people_comboBox.setEnabled(True)  # 允许选择人物

    

 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setWindowTitle("文字转语音工具")
    window.show()
    sys.exit(app.exec())